<template>
  <view class="container">
    <!-- 顶部组件 -->
    <u-navbar
      id="nav-bar"
      :is-back="true"
      :background="{ background: '#fff' }"
      :border-bottom="false"
      title="确认订单"
    ></u-navbar>

    <view class="confirmOrder-wrap">
      <view v-if="deliveryType == 0" class="address" @click="handleChooseAddr">
        <view v-if="addressInfo" class="center">
          <view class="item-top">
            <text> {{ addressInfo.regionName }} </text>
            <view v-if="addressInfo.isDefault" class="tag">默认</view>
          </view>
          <view class="item-center">{{ addressInfo.address }}</view>
          <view class="item-bottom">
            <view class="name">{{ addressInfo.name }}</view>
            <view class="phone">{{ addressInfo.phone }}</view>
          </view>
        </view>
        <view v-else class="center">取货人联系方式</view>
        <u-icon name="arrow-right" :size="36" color="#CCCCCC"></u-icon>
      </view>

      <!-- 订单列表 -->
      <view class="order-list">
        <view class="order-item">
          <view class="order-item-in">
            <view class="order-item-header">
              <view class="header-title">
 <!--               <image
                  src="../../static/images/cart-dp.png"
                  mode="widthFix"
                ></image> -->
                <text>自营店</text>
              </view>
            </view>
            <view
              v-for="(item, index) in productDataList"
              class="order-goods"
              :key="index"
            >
              <image :src="item.imgUr.split('|')[0]" mode="widthFix"></image>
              <view class="goods-right">
                <view class="title">{{ item.name }}</view>
                <view class="label">{{ item.specLabel || '' }}</view>
                <view class="bottom">
                  <view class="price">
                    <text>￥</text>{{ item.price || 0 }}
                  </view>
                  <view class="count"
                    >单价:{{ item.price / item.count || 0 }}&nbsp;&nbsp;共{{
                      item.count || 0
                    }}件</view
                  >
                </view>
              </view>
            </view>

            <view class="delAdRem">
              <view class="left">订单备注</view>
              <view class="right"
                ><u-input
                  v-model="remarks"
                  :border="false"
                  placeholder="选填，请先和商家协商一致"
                />
              </view>
            </view>

            <!-- <view class="order-item-footer"
              ><view class="footer-price"
                ><text class="total">共{{ totalNum }}件</text>小计：<text
                  class="unit"
                  >¥</text
                ><text class="num">{{ totalAmount }}</text></view
              >
            </view> -->
          </view>
        </view>
        <view class="order-item">
          <view class="order-item-in" style="padding: 0 30rpx">
            <view class="delAdRem">
              <view class="left">商品金额</view>
              <view class="right price">￥{{ totalAmount || 0 }}</view>
            </view>
            <view class="delAdRem">
              <view class="left">快递配送</view>
              <view class="right">
                <u-radio-group
                  v-model="deliveryType"
                  @change="deliveryTypeChange"
                >
                  <u-radio :name="0">物流配送</u-radio>
                  <u-radio :name="1">门店自提</u-radio>
                </u-radio-group>
              </view>
            </view>

            <view v-if="totalBackIntegral > 0" class="delAdRem">
              <view class="left">赠活力值<text>购买专区商品可获得</text></view>
              <view class="right integral">
                {{ totalBackIntegral || 0 }}活力值
              </view>
            </view>
            <view v-if="totalBackIntegral < 0" class="delAdRem">
              <view class="left">消耗活力值<text>购买商品消耗</text> </view>
              <view class="right integral">
                {{ -totalBackIntegral || 0 }}活力值
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="address mt30" @click="handleChooseArea">
        <view v-if="areaInfo" class="center">
          <view class="item-top">
            <text> {{ areaInfo.areaName }} </text>
          </view>
          <view class="item-center">{{ areaInfo.areaAddress }}</view>
        </view>
        <view v-else class="center">请先选择自提门店</view>
        <u-icon name="arrow-right" :size="36" color="#CCCCCC"></u-icon>
      </view>
    </view>

    <!-- 结算 -->
    <view class="settlement">
      <view class="settlement-in">
        <!-- <text class="num">共{{ totalNum }}件</text> -->
        <view class="left">
          抵扣
          <text class="price"> ￥{{ totalAmount || 0 }} </text>
        </view>
        <view class="left">
          支付
          <text class="price"> ￥{{ totalAmount || 0 }} </text>
        </view>
        <view class="btn" @click="confirm()">确认申领</view>
      </view>
    </view>

    <!-- 选择支付方式 -->
    <js-payment-method
      ref="paymentMethodRef"
      :price="totalAmount"
      @sure="handlePayNow"
    ></js-payment-method>
  </view>
</template>
<script>
import service from '@/common/service.js';
import JsPaymentMethod from '@/components/js-paymentMethod';

export default {
  components: {
    JsPaymentMethod,
  },
  data() {
    return {
      baseFileUrl: service.getBaseFileUrl(),
      tradeId: null,
      addressInfo: null,
      areaInfo: null,
      anonymous: true,
      remarks: '',
      goodsData: {},
      products: [],
      productDataList: [],
      totalNum: 1,
      totalAmount: 0,
      totalBackIntegral: 0,
      buyType: 0,
      showPayView: false,
      payWay: 51,
      specLabel: '',
      detailCount: 0,
      specCode: '',
      specPrice: 0,
      myAccount: {},
      specBackIntegral: 0,
      deliveryType: 0,
    };
  },
  onLoad(e) {
    if (e.specCode) {
      this.specCode = e.specCode;
    }
    if (e.specLabel) {
      this.specLabel = e.specLabel;
    }
    if (e.buyNum) {
      this.detailCount = Number(e.buyNum);
    }
    if (e.specPrice) {
      this.specPrice = Number(e.specPrice);
    }
    if (e.specBackIntegral) {
      this.specBackIntegral = Number(e.specBackIntegral);
    }
    if (e.buyType) {
      this.buyType = Number(e.buyType);
    }
    if (e.id) {
      this.getData(e.id);
    } else {
      let products = uni.getStorageSync('tempProducts');
      let productDataList = uni.getStorageSync('tempProductDataList');
      let totalNum = 0;
      let totalAmount = 0;
      let totalBackIntegral = 0;

      productDataList.forEach((item) => {
        totalNum += item.count;
        totalAmount += parseFloat(item.price);
        if (item.buyType == 1) {
          totalBackIntegral -= parseFloat(item.backIntegral) * item.count;
        } else {
          totalBackIntegral += parseFloat(item.backIntegral) * item.count;
        }
      });

      this.totalNum = totalNum;
      this.totalAmount = parseFloat(totalAmount).toFixed(2);
      this.totalBackIntegral = totalBackIntegral;
      this.products = products;
      this.productDataList = productDataList;
    }
  },
  onShow() {
    const _this = this;
    uni.$on('addressData', (rel) => {
      _this.addressInfo = rel.addressInfo;
    });
    uni.$on('areaInfo', (rel) => {
      _this.areaInfo = rel.areaInfo;
    });
    this.getOrderIsPaid();
    if (!_this.addressInfo) {
      this.getDefaultAddress();
    }
  },
  methods: {
    deliveryTypeChange(value) {
      this.deliveryType = value;
    },
    getOrderIsPaid() {
      if (!this.tradeId) {
        return;
      }
      const that = this;
      service.getOrderIsPaid(
        {
          id: that.tradeId,
        },
        function (res) {
          if (res && res.code == '0000') {
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/order/index?tab=2',
              });
            }, 1500);
          }
        },
        function (res) {}
      );
    },
    getData(id) {
      const that = this;
      const param = {
        id: id,
      };
      service.getGoodsDetail(
        param,
        function (res) {
          if (res && res.code == '0000') {
            const { data } = res;
            that.goodsData = data;
            that.totalAmount = parseFloat(
              that.detailCount *
                (that.specPrice ? that.specPrice : data.salePrice)
            ).toFixed(2);
            that.totalBackIntegral = parseFloat(
              that.backIntegral * that.detailCount
            ).toFixed(2);
            if (data.buyType == 1) {
              that.totalBackIntegral = -parseFloat(
                data.backIntegral * that.detailCount
              ).toFixed(2);
            } else {
              that.totalBackIntegral = parseFloat(
                data.backIntegral * that.detailCount
              ).toFixed(2);
            }
            that.totalNum = that.detailCount;
            let product = {
              productId: id,
              num: that.detailCount,
            };
            if (
              that.specCode != '' &&
              that.specCode != 'null' &&
              that.specCode != null
            ) {
              product = {
                productId: id,
                num: that.detailCount,
                skuCode: that.specCode,
              };
            }
            that.products.push(product);
            let productData = {
              id: data.id,
              name: data.productName,
              specLabel: that.specLabel,
              imgUr: that.baseFileUrl + data.productImg,
              singlePrice: that.specPrice ? that.specPrice : data.salePrice,
              price: parseFloat(
                that.detailCount *
                  (that.specPrice ? that.specPrice : data.salePrice)
              ).toFixed(2),
              count: that.detailCount,
              checked: false,
            };
            that.productDataList.push(productData);
          }
        },
        function (res) {}
      );
    },
    getDefaultAddress() {
      const that = this;
      service.getDefaultAddress(
        {},
        function (res) {
          if (res && res.code == '0000') {
            that.addressInfo = res.data;
            if (!that.addressInfo) {
              uni.showModal({
                title: '提示',
                content: '请先添加收货地址',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#A21E19',
                success: function (res) {
                  uni.navigateTo({
                    url: '/pages/address/index',
                  });
                },
              });
            }
          }
        },
        function (res) {}
      );
    },
    handleChooseAddr() {
      uni.navigateTo({
        url: '../address/chooseAddress',
      });
    },
    handleChooseArea() {
      uni.navigateTo({
        url: '../address/chooseArea',
      });
    },
    radioChange(payWay) {
      this.payWay = payWay;
    },
    confirm() {
      const that = this;
      if (that.deliveryType == 0 && !that.addressInfo) {
        uni.showModal({
          title: '提示',
          content: '请先选择收货地址',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#A21E19',
          success: function (res) {
            uni.navigateTo({
              url: '/pages/address/index',
            });
          },
        });
        return;
      }
      if (that.deliveryType == 1 && !that.areaInfo) {
        uni.showModal({
          title: '提示',
          content: '请先选择自提门店',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#A21E19',
          success: function (res) {
            uni.navigateTo({
              url: '/pages/address/chooseArea',
            });
          },
        });
        return;
      }
      that.$refs.paymentMethodRef.showPopup();
    },
    handlePayNow(payWay) {
      const that = this;

      var params = {};
      if (that.deliveryType == 0) {
        params = {
          addressId: that.addressInfo.id,
          deliveryType: that.deliveryType,
          products: that.products,
          payWay: payWay,
          remarks: that.remarks,
        };
      } else {
        params = {
          areaId: that.areaInfo.id,
          deliveryType: that.deliveryType,
          products: that.products,
          payWay: payWay,
          remarks: that.remarks,
        };
      }
      uni.showLoading({
        title: '支付中',
      });
      service.addOrder(
        params,
        function (res) {
          if (res && res.code == '0000') {
            uni.hideLoading();
            if (res.data.needPay) {
              if (res.data.payLink) {
                // #ifdef APP-PLUS
                plus.runtime.openURL(res.data.payLink);
                // #endif
                // #ifdef H5
                window.location.href = res.data.payLink;
                // #endif
              } else if (res.data.payJson) {
                wx.requestPayment({
                  timeStamp: res.data.payJson.timeStamp,
                  nonceStr: res.data.payJson.nonceStr,
                  package: res.data.payJson.packageVal,
                  signType: res.data.payJson.signType,
                  paySign: res.data.payJson.paySign,
                  success: function (res) {
                    that.$refs.paymentMethodRef.closePopup();
                    uni.navigateTo({
                      url: '/pages/order/index?tab=2',
                    });
                  },
                  fail: function (res) {
                    console.info(res);
                  },
                  complete: function (res) {
                    console.info(res);
                  },
                });
              }
            } else {
              that.$refs.paymentMethodRef.closePopup();
              uni.navigateTo({
                url: '/pages/order/index?tab=2',
              });
            }
          }
        },
        function (res) {}
      );
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f7f7f7;
}

.container {
  width: 100%;
  min-height: 100vh;
  padding: 0;
  text-align: center;
  background-color: #f7f7f7;
}

.mt30 {
  margin-top: 30rpx;
}

.confirmOrder-wrap {
  width: 100%;
  padding: 30rpx 30rpx 200rpx 30rpx;

  .address {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 30rpx 24rpx;
    width: 100%;
    background-color: #ffffff;
    border-radius: 10rpx;

    .center {
      flex: 1;
      padding: 0 20rpx;
      line-height: 1;

      .item-top {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        font-weight: normal;
        font-size: 26rpx;
        color: #222222;

        .name {
          font-size: 26rpx;
          color: #2f2f2f;
        }

        text {
          margin-left: 10rpx;

          &:first-child {
            margin-left: 0;
          }
        }

        .tag {
          margin-left: 25rpx;
          width: 52rpx;
          height: 26rpx;
          line-height: 26rpx;
          font-size: 18rpx;
          font-weight: normal;
          color: #ffffff;
          text-align: center;
          background: #a21e19;
          border-radius: 5rpx;
        }
      }

      .item-center {
        margin-top: 18rpx;
        font-size: 32rpx;
        font-weight: normal;
        color: #222222;
        line-height: 1.5;
        text-align: left;
      }

      .item-bottom {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-top: 18rpx;
        font-size: 26rpx;

        .name {
          font-size: 26rpx;
          color: #2f2f2f;
        }

        .phone {
          margin-left: 20rpx;
          font-size: 26rpx;
          color: #2f2f2f;
        }
      }
    }
  }
}

.order-list {
  width: 100%;
  background-color: transparent;

  .order-item {
    margin-top: 30rpx;
    width: 100%;
    background-color: #fff;
    border-radius: 10rpx;

    .order-item-in {
      width: 100%;
      padding: 30rpx 24rpx;
      overflow: hidden;

      .order-item-header {
        float: left;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        width: 100%;

        .header-title {
          display: flex;
          flex-direction: row;
          justify-content: flex-start;
          align-items: center;

          image {
            width: 32rpx;
          }

          text {
            margin-left: 10rpx;
            font-size: 26rpx;
            font-weight: bold;
            color: #000000;
            line-height: 1;
          }
        }
      }

      .order-goods {
        float: left;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        width: 100%;
        padding: 25rpx 0;

        image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 10rpx;
        }

        .goods-right {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          justify-content: flex-start;
          padding: 0 20rpx;

          .title {
            font-size: 26rpx;
            font-weight: bold;
            color: #000000;
            line-height: 1.5;
            text-align: left;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .label {
            margin-top: 12rpx;
            width: 100%;
            height: 42rpx;
            line-height: 42rpx;
            padding: 0 15rpx;
            font-weight: 400;
            color: #999393;
            font-size: 22rpx;
            background: #f7f7f7;
            border-radius: 10rpx;
            text-align: left;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .bottom {
            margin-top: 20rpx;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            width: 100%;

            .price {
              font-size: 42rpx;
              font-weight: bold;
              color: #e52e2e;

              text {
                font-size: 24rpx;
                font-weight: normal;
              }
            }

            .count {
              font-size: 24rpx;
              font-weight: 400;
              color: #999999;
            }
          }
        }
      }

      .order-item-footer {
        float: left;
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        align-items: center;
        width: 100%;

        .footer-price {
          margin-top: 30rpx;
          font-size: 26rpx;
          font-weight: 400;
          color: #222222;

          .total {
            margin-right: 10rpx;
            font-size: 24rpx;
            font-weight: 400;
            color: #999999;
            line-height: 1;
          }

          .unit {
            line-height: 1;
            font-size: 24rpx;
            font-weight: normal;
            color: #e52e2e;
          }

          .num {
            line-height: 1;
            font-size: 36rpx;
            font-weight: normal;
            color: #e52e2e;
          }
        }
      }
    }
  }
}

.delAdRem {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 25rpx 0;
  line-height: 1;

  .left {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    font-size: 26rpx;
    font-weight: 400;
    color: #222222;

    text {
      margin-left: 40rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: #999393;
    }
  }

  .right {
    flex: 1;
    padding-left: 40rpx;
    font-size: 28rpx;
    font-weight: 400;
    color: #222222;
    text-align: right;

    /deep/ .u-input__input {
      font-size: 24rpx;
    }

    .tag {
      padding: 7rpx 15rpx;
      font-size: 18rpx;
      font-weight: normal;
      color: #ffffff;
      line-height: 1;
      background: #a21e19;
      border-radius: 8rpx;
    }
  }

  .integral,
  .price {
    color: #a21e19;
  }
}

.settlement {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 30rpx 30rpx 60rpx;
  line-height: 1;
  background-color: #ffffff;

  .settlement-in {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 0;

    .left {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      font-size: 28rpx;
      color: #333333;
      .num {
        margin-right: 10rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #999999;
      }

      .price {
        color: #e52e2e;
        font-weight: bold;
      }
    }

    .btn {
      width: 200rpx;
      height: 74rpx;
      line-height: 74rpx;
      font-size: 26rpx;
      font-weight: normal;
      color: #fff;
      text-align: center;
      background: linear-gradient(90deg, #332108, #201403);
      border-radius: 12rpx;
    }
  }
}
</style>
